<!-- 顶部Tab路由导航栏 -->
<template>
    <div class="box">
        <div id="my-container">
            <el-tabs v-model="editableTabsValue" type="card" :closable="editableTabs.length > 1" class="demo-tabs"
                @tab-remove="handleTabsEdit" @tab-change="goTabPage">
                <el-tab-pane v-for="item in editableTabs" :label="item.title" :name="item.path" lazy>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { useDraggable } from 'vue-draggable-plus'

const router = useRouter()//全部路由对象
const route = useRoute()//当前活跃的路由对象

//高亮的tab
const editableTabsValue = ref(route.path)
//Tab标签数组
const editableTabs = ref([
    {
        title: route.meta.title as string,
        path: route.path,
    },
])
//监听Tab栏数组
watch(editableTabs, (newVal) => {
    // 存储到本地存储中
    localStorage.setItem('editableTabs', JSON.stringify(newVal))
}, { deep: true })

onMounted(() => {
    // 读取本地存储中的editableTabs
    let localTabs = JSON.parse(localStorage.getItem('editableTabs') || '[]')
    if (localTabs.length > 0) editableTabs.value = localTabs
})
//路由守卫  跳转前触发
onBeforeRouteUpdate((to) => {
    // 找到当前跳转的tab在tabs中的下标
    let sum = editableTabs.value.findIndex((item: any) => {
        return item.path === to.path
    })
    // 如果没有找到，添加新tab
    if (sum == -1) {
        editableTabs.value.push({
            title: to.meta.title as string,
            path: to.path,
        })
        editableTabsValue.value = to.path//设置高亮tab
    } else {
        editableTabsValue.value = to.path//设置高亮tab
    }
})
//点击跳转
const goTabPage = (path: any) => {
    router.push(path)//跳转页面
    editableTabsValue.value = path//设置高亮tab
}
//点击 tab 移除按钮后触发
const handleTabsEdit = (name: string) => {
    //判断删除的是不是当前高亮的tab
    if (route.path === name) {
        // 删除当前高亮的tab
        editableTabs.value = editableTabs.value.filter((tab) => tab.path !== name)
        // 跳转到最后一项的页面
        router.push(editableTabs.value[editableTabs.value.length - 1].path)
    } else {
        editableTabs.value = editableTabs.value.filter((tab) => tab.path !== name)
    }
}

//拖拽效果
useDraggable('#my-container .el-tabs__nav', editableTabs, { animation: 1000 })
</script>

<style scoped lang="less">
.box {
    position: relative;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 999;
    // padding-top: 10px;
    // padding-left: 2px;

    // box-shadow: 0 5px 10px rgba(0, 0, 0, 0.463);
}

// :deep(.el-tabs__nav:first-child) {
//     background-color: black !important;
// }</style>